﻿using System;
using System.Collections;
using System.IO;
using System.Xml;

namespace UDS.Management
{
    /// <summary>
    /// Defines the callback method for serializing an element.
    /// </summary>
    public delegate void WriteElement(XmlWriter writer, object obj);

    /// <summary>
    /// Defines several helper methods.
    /// </summary>
    internal static class Utility
    {
        /// <summary>
        /// The generated xml looks like:
        /// [root]
        ///     [elm id="" /]
        ///     [elm id="" /]
        ///     ....
        /// [/root]
        /// </summary>
        public static string GenerateXML(IEnumerable e, string root, WriteElement w)
        {
            if (string.IsNullOrEmpty(root))
            {
                throw new ArgumentNullException("root");
            }
            if (w == null)
            {
                throw new ArgumentNullException("w");
            }

            using (var sw = new StringWriter())
            {
                var settings = new XmlWriterSettings();
                settings.ConformanceLevel = ConformanceLevel.Document;
                settings.OmitXmlDeclaration = true;
                settings.Indent = false;

                using (XmlWriter writer = XmlWriter.Create(sw, settings))
                {
                    writer.WriteStartElement(root);
                    if (e != null)
                    {
                        foreach (object obj in e)
                        {
                            if (obj != null)
                            {
                                w(writer, obj);
                            }
                        }
                    }
                    writer.WriteEndElement();
                }

                return sw.GetStringBuilder().ToString();
            }
        }
    }
}
